/**
 * Copyright 2007-2011 Vidar Svansson
 *
 * This file is part of JAdapter.
 *
 * JAdapter is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * JAdapter is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with JAdapter.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.jadapter.adapters;

import org.jadapter.annotations.DefaultValue;

import java.lang.reflect.Type;
import java.lang.reflect.ParameterizedType;

/**
 * User: vs
 * Date: 13.6.2009
 * Time: 09:43:11
 */
public class Adapters {

    private Adapters(){}

    static <T> Class<T>  getClass(Type type) {
        if(type == null){
            return null;
        }
        if(type instanceof Class) {
            @SuppressWarnings("unchecked")
            Class<T> klass =  (Class<T>)type;
            if(klass.equals(DefaultValue.class)){
                return null;
            }
            return klass;
        }
        if(type instanceof ParameterizedType){
            Type raw = ((ParameterizedType)type).getRawType();
            return getClass(raw);

        }

        throw new UnsupportedOperationException("unknown type " + type.getClass());
    }


    public static boolean isInstance(Class<?> returnType, Type type) {
        return type instanceof Class && getClass(type).isAssignableFrom(returnType);
    }

    public static boolean isInstance(Object instance, Type type) {
        return type instanceof Class && getClass(type).isInstance(instance);
    }


}
